<?php
namespace app\v2\model;

use think\Model;
use llpay\lib\LLpaySubmit;
use llpay\lib\LLpayNotify;
use think\Db;
use app\admin\logic\Pay as LPay;
use app\common\model\HcPay;



/**
 * 支付类
 */
class Pay extends Model
{
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai');
        $this->notify_url = config('domainpath')['api'].'/v2/notify';  //还款异步回调地址
        $this->return_url = config('domainpath')['api'].'/v2/successPage';  //还款同步地址 （成功页面）
    }
    public function notice($dr)
    {
        $hcPay = new HcPay;
        //验签
        $sign = $hcPay->signEncode($dr);
        if($sign != $dr['sign'])
        {
            file_put_contents(LOGS_DIR_NAME."notify_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:验签失败[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
        }
        $OrderModel =  new Order();
        $update = $OrderModel->payAfter($dr);
        unset($dr['sign']);
        if(!$update){
            $fail_info = $OrderModel->getError();
            file_put_contents(LOGS_DIR_NAME."notify_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:订单数据更新失败[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
            return "FAILED";
        }
        file_put_contents(LOGS_DIR_NAME."notify_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:订单数据更新成功[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
        return "SUCCESS";

    }

    /**
     * 申请订单认证回调
     * @author cxr <1481746137@qq.com>
     * @param $dr
     * @return string
     */
    public function apply_notice($dr)
    {
        $hcPay = new HcPay;
        //验签
        $sign = $hcPay->signEncode($dr);
        if($sign != $dr['sign'])
        {
            file_put_contents(LOGS_DIR_NAME."notify_apply_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:验签失败[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
        }
        $OrderModel =  new ApplyOrder();
        $update = $OrderModel->ApplyNotify($dr);
        unset($dr['sign']);
        if(!$update){
            $fail_info = $OrderModel->getError();
            file_put_contents(LOGS_DIR_NAME."notify_apply_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:订单数据更新失败[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
            return "FAILED";
        }
        file_put_contents(LOGS_DIR_NAME."notify_apply_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:订单数据更新成功[".$fail_info."] 回调详情:".json_encode($dr)."\n\n", FILE_APPEND);
        return "SUCCESS";

    }

    public function getLlPay($param=array()) {    
        $this->error = "此接口已弃用";
        return false;  
        /**************************请求参数**************************/

        //姓名
        $acct_name = $param['name'];

        //身份证号
        $id_no =  $param['id_card']; 

        //银行卡号
        $card_no = ''; 

        //商户用户唯一编号
        $user_id = $param['rand_code'];

        //商户订单号（商户网站订单系统中唯一订单号，必填）
        $no_order = $param['no_order'];

        //付款金额（必填）
        $money_order = $param['money_order'];

        //协议号
        $no_agree = $param['no_agree'];

        //订单描述
        $info_order = $param['info_order'] ? $param['info_order'] : "还款";

        //商品名称
        $name_goods = $info_order;

        //支付类型
        $busi_partner = $param['busi_partner'] ? $param['busi_partner'] : 101001;

        //风险控制参数
        $risk_item = array(
            'frms_ware_category' => 2010, //商品类目传 2010
            'user_info_mercht_userno' => $param['rand_code'], //用户id
            'user_info_bind_phone' => $param['phone'],  //用户手机号
            'user_info_dt_register' => $param['reg_time'], //用户注册时间 格式：YYYYMMDDH24MISS 14 位数字，精确到秒
            'user_info_identify_state' => 1, //是否实名认证
            'user_info_identify_type' => 1, //实名认证方式
            'user_info_full_name' => $param['name'], //用户姓名
            'user_info_id_no' => $param['id_card'] //用户身份证号
        );

        //服务器异步通知页面路径[需http://格式的完整路径，不能加?id=123这类自定义参数]
        $notify_url = $this->notify_url;

        //页面跳转同步通知页面路径[需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/]
        $return_url =  $this->return_url;

        /************************************************************/

        $llpay_config = config('llpay');

        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner" => trim($llpay_config['oid_partner']),
            "app_request" => trim($llpay_config['app_request']),
            "sign_type" => trim($llpay_config['sign_type']),
            "valid_order" => trim($llpay_config['valid_order']),
            "user_id" => $user_id,
            "busi_partner" => $busi_partner,
            "no_order" => $no_order,
            "dt_order" => local_date('YmdHis', time()),
            "name_goods" => $name_goods,
            "info_order" => $info_order,
            "money_order" => $money_order,
            "notify_url" => $notify_url,
            "url_return" => $return_url,
            "card_no" => $card_no,
            "acct_name" => $acct_name,
            "id_no" => $id_no,
            "no_agree" => $no_agree,
            "risk_item" => $risk_item,
            "bg_color" => '2f89ff',
        );
        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);
        // $html_text = $llpaySubmit->buildRequestForm($parameter, "get", "确认");
        $html_text = $llpaySubmit->buildRequestLink($parameter);
        $data['url'] = $html_text;
        $data['parameter'] = $parameter;
        return $data;        
    }



    /**
     * 查询订单信息
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-14T09:35:21+0800
     * @param     $order_info  订单信息  
     * @return      
     */
    public function queryPay($order_info)
    {
        //单号
        $no_order = $order_info->no_order; 

        //时间
        $dt_order = $order_info->dt_order;

        $llpay_config = config('llpay');
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner" => trim($llpay_config['oid_partner']),
            "sign_type" => trim($llpay_config['sign_type']),
            "query_version" => trim($llpay_config['version']),
            "no_order" => $no_order,
            "dt_order" => $dt_order,
        );

        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);

        // 查询 订单信息
        $html_text = $llpaySubmit->buildQueryPayRequestHttp($parameter); 
        $res_Arr = $this->object_array(json_decode($html_text));
        # 判断是否有 sign 如果没有 说明没有查询到订单 ，无需走验签流程
        if(!isset($res_Arr["sign"])){
            $this->error = $res_Arr["ret_msg"].":".$res_Arr["ret_code"];
            return false;
        }        
        $verify_res = $this->query_notice($html_text);
//  结果示例
// array(2) {
//   ["res"] => bool(true)
//   ["data"] => array(14) {
//     ["oid_partner"] => string(18) "201709220000945943"
//     ["sign_type"] => string(3) "RSA"
//     ["dt_order"] => string(14) "20171012194354"
//     ["no_order"] => string(20) "2017101112042188XQ57"
//     ["oid_paybill"] => string(16) "2017101264863574"
//     ["money_order"] => string(4) "0.01"
//     ["result_pay"] => string(7) "SUCCESS"
//     ["settle_date"] => string(8) "20171012"
//     ["info_order"] => string(21) "续期还款 第57次"
//     ["pay_type"] => string(1) "D"
//     ["bank_code"] => string(8) "01040000"
//     ["ret_code"] => string(4) "0000"
//     ["ret_msg"] => string(12) "交易成功"
//     ["bank_name"] => string(12) "中国银行"
//   }
// }
        if ($verify_res["res"]) { //验证成功
            //获取连连支付的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $no_order = $verify_res["data"]['no_order'];//商户订单号
            $oid_paybill = $verify_res["data"]['oid_paybill'];//连连支付单号
            $result_pay = $verify_res["data"]['result_pay'];//支付结果，SUCCESS：为支付成功
            $money_order = $verify_res["data"]['money_order'];// 支付金额

            switch ($verify_res["data"]['result_pay']) {
                case 'SUCCESS':
                    $verify_res["data"]['ret_msg'] = '成功'; 
                    break;                
                case 'WAITING':
                    $verify_res["data"]['ret_msg'] = '等待支付'; 
                    break;                
                case 'PROCESSING':
                    $verify_res["data"]['ret_msg'] = '银行支付处理中'; 
                    break;                
                case 'REFUND':
                    $verify_res["data"]['ret_msg'] = '退款'; 
                    break;                
                case 'FAILURE':
                    $verify_res["data"]['ret_msg'] = '失败'; 
                    break;
            }

            $OrderModel =  new Order();
            $update = $OrderModel->payAfter($verify_res['data']);
            if(!$update){
                $fail_info = $OrderModel->error;
                $verify_res["data"]['ret_msg'] = $fail_info.'，请联系客服';
                file_put_contents(LOGS_DIR_NAME."failure.txt", '时间:'.date('Y-m-d H:i:s',time()).' 异常原因:'.$fail_info.' 回调详情:'.json_encode($verify_res["data"])."\n\n", FILE_APPEND);
            }

            return $verify_res["data"];
        } else {
            $this->error = "返回结果验签失败";
            return false;
        }  

    }
    public function query_notice($str)
    {

        $llpay_config = config('llpay');
        //计算得出通知验证结果
        $llpayNotify = new LLpayNotify($llpay_config);

        // 订单查询验签
        $llpayNotify->verifyNotify_Query($str);

        $data["res"] = $llpayNotify->result; 
        $data["data"] = $llpayNotify->notifyResp;
        return $data; 
    }
    /**
     * 银行卡 bin 信息查询
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-14T10:16:42+0800
     */
    public function BinQuery($card_no=null)
    {
        //卡号
        if(is_null($card_no)){
            $this->error = "没有获取到正确的卡号信息";
            return false;
        }    

        $llpay_config = config('llpay');
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner" => trim($llpay_config['oid_partner']),
            "sign_type" => trim($llpay_config['sign_type']),
            "card_no" => $card_no,
        );
        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);
        // 查询 订单信息
        $html_text = $llpaySubmit->buildBinQueryRequestHttp($parameter);        

        $res_Arr = $this->object_array(json_decode($html_text));
        # 判断是否有 sign 如果没有 说明没有查询到订单 ，无需走验签流程
        if(!isset($res_Arr["sign"])){
            $this->error = $res_Arr["ret_msg"].$res_Arr["ret_code"];
            return false;
        } 
        $verify_res = $this->Bin_notice($html_text);

//  返回示例       
// array(2) {
//   ["res"] => bool(true)
//   ["data"] => array(6) {
//     ["sign_type"] => string(3) "RSA"
//     ["card_type"] => string(1) "2"     // 2是储蓄卡 3 信用卡
//     ["ret_code"] => string(4) "0000"
//     ["ret_msg"] => string(12) "交易成功"
//     ["bank_name"] => string(18) "中国建设银行"
//     ["bank_code"] => string(8) "01050000"
//   }
// }
        if ($verify_res["res"]) { //验证成功
            unset($verify_res["data"]["ret_msg"]);
            unset($verify_res["data"]["ret_code"]);
            unset($verify_res["data"]["sign_type"]);
            $verify_res["data"]['card_no'] = $card_no;
            return $verify_res["data"];
        } else {
            $this->error = "返回结果验签失败";
            return false;
        }           
    }
    public function Bin_notice($str)
    {

        $llpay_config = config('llpay');
        //计算得出通知验证结果
        $llpayNotify = new LLpayNotify($llpay_config);

        // 订单查询验签
        $llpayNotify->verifyNotify_Bin($str);

        $data["res"] = $llpayNotify->result; 
        $data["data"] = $llpayNotify->notifyResp;
        return $data; 
    }


/**
 * 银行卡签约申请
 * @author   yhq <934797303@qq.com>
 * @DateTime 2017-10-20T12:03:10+0800
 * @param    [type]                   $param [description]
 * @return   [type]                          [description]
 */
    public function bankcardbind($param)
    {       
        $this->error = "此接口已弃用";
        return false; 

        $applyModel = new Apply;
        $canBindBank = $applyModel->canBindBank($param['uid']);
        if($canBindBank == false){
            $this->error = "申请中不能绑定";
            return false; 
        }

        // 限制同一身份证绑定多个账号
        $UserInfoModel = new UserInfo;
        $map['id_card'] = $param['id_card'];
        $map['uid']     = ['neq', $param['uid']];
        $userInfo = $UserInfoModel->where($map)->find();
        if(!empty($userInfo)){
            $str = $userInfo['phone'];
            $phone = substr($str,0,3).'****'.substr($str,-4);
            $this->error = "该身份证已经被{$phone}绑定";
            return false; 
        }
        
        $time_stamp = date('YmdHis');
        
        //风险控制参数
        $risk_item = array(
            'frms_ware_category' => 2010, //商品类目传 2010
            'user_info_mercht_userno' => $param['rand_code'], //用户id
            'user_info_bind_phone' => $param['bind_phone'],  //用户手机号
            'user_info_dt_register' => $time_stamp, //用户注册时间 格式：YYYYMMDDH24MISS 14 位数字，精确到秒
            'user_info_identify_state' => 1, //是否实名认证
            'user_info_identify_type' => 4, //实名认证方式
            'user_info_full_name' => $param['name'], //用户姓名
            'user_info_id_no' => $param['id_card'] //用户身份证号
        );

        $llpay_config = config('llpay');
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "api_version"      => '1.0',
            "sign_type"        => trim($llpay_config['sign_type']),
            "oid_partner"      => trim($llpay_config['oid_partner']),
            "app_request"      => trim($llpay_config['app_request']),
            "time_stamp"       => $time_stamp,
            "user_id"          => $param['rand_code'],
            "no_order"         => $param['no_order'],
            "dt_order"         => $time_stamp,
            "risk_item"        => $risk_item,
            "flag_pay_product" => '1',
            "flag_chnl"        => '3',
            "id_type"          => '0',
            "id_no"            => $param['id_card'],
            "acct_name"        => $param['name'],
            "card_no"          => $param['bank_card_number'],
            "notify_url"       => $notify_url,
            "bind_mob"         => $param['bind_mob'],
        );

        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);
        $html_text = $llpaySubmit->buildbankcardbindRequestHttp($parameter); 

        $arr = json_decode($html_text,true);
        if($arr['ret_code'] == '0000'){

// $arr 示例
// array(9) {
//   ["sign"] => string(172) "L6SWs+l5dKsKS6rz2J2DKlb2q"
//   ["correlationID"] => string(36) "4ae05b23-17ff-45df-ad5b-b8e72cc06e94"
//   ["ret_code"] => string(4) "0000"
//   ["no_order"] => string(16) "2017102610197484"
//   ["oid_partner"] => string(18) "201710130001019170"
//   ["token"] => string(32) "97D31527E8722A9FAA9F59DD181EEFC9"
//   ["sign_type"] => string(3) "RSA"
//   ["ret_msg"] => string(12) "交易成功"
//   ["user_id"] => string(2) "36"
// }

            $data['llpay']['oid_partner']      = $arr['oid_partner'];
            $data['llpay']['user_id']          = $arr['user_id'];
            $data['llpay']['token']            = $arr['token'];
            $data['llpay']['no_order']         = $arr['no_order'];
            $data['llpay']['time_stamp']       = $time_stamp;
            $data['llpay']['api_version']      = '1.0';
            $data['llpay']['flag_chnl']        = '3';

            $data['bankInfo']['name']             = $param['name'];
            $data['bankInfo']['id_card']          = $param['id_card'];
            $data['bankInfo']['bind_mob']         = $param['bind_mob'];
            $data['bankInfo']['bank_card_number'] = $param['bank_card_number'];
            
            return $data;
        }else{
            $this->error = $arr['ret_msg'];
            return false;
        }

    }

    /**
     * 保存银行卡
     * @return [type]        [description]
     */
    public function saveBankCard($param)
    {
        $this->error = "此接口已弃用";
        return false;  

        $signData = array(
            'sign'        => $param['sign'],
            'ret_code'    => $param['ret_code'],
            'no_order'    => $param['no_order'],
            'oid_partner' => $param['oid_partner'],
            'no_agree'    => $param['no_agree'],
            'sign_type'   => $param['sign_type'],
            'ret_msg'     => $param['ret_msg'],
            'dt_order'    => $param['dt_order'],
            'user_id'     => $param['user_id'],
        );

        $verify_res = $this->bankcardbindlistQuery_notice($signData);

        if ($verify_res["res"]) { //验签成功

            //新增认证时间
            $param['bank_auth_date'] = date('Y-m-d H:i:s', time());

            $UserInfoModel = new UserInfo;
            $update = $UserInfoModel->allowField(true)->save($param, ['uid'=>$param['uid']]);
            if(false!==$update){
                return true;
            }
            $this->error ='绑定失败';
            return false;
        }
        $this->error ='返回结果验签失败';
        return false;
    }


    /**
     * 银行卡列表
     * @author   yhq <934797303@qq.com>
     * @DateTime 2018-03-17T17:05:54+0800
     * @param    [type]                   $uid    [description]
     * @param    string                   $offset [description]
     * @param    boolean                  $sleep  [description]
     * @return   [type]                           [description]
     */
    public function bankcardbindlistQuery($uid=null,$offset='0',$sleep=true)
    {
        if(is_null($uid)){
            $this->error = "没有获取到正确的用户信息";
            return false;
        }  
        $UserInfoModel = new UserInfo();
        $UserInfo = $UserInfoModel->where('uid',$uid)->field('bank_card_number,name')->find();
        if(empty($UserInfo['bank_card_number'])){
            return [];
        }

        // $data[] = [
        //     'back_url'  => '',
        //     'bank_code' => '',
        //     'bank_name' => '未知银行',
        //     'card_no'   => substr($UserInfo['bank_card_number'],-4),
        //     'card_type' => '',
        //     'color'     => '',
        //     'logo_url'  => '',
        //     'no_agree'  => '',
        // ];

        $data = [];

        // 支付宝接口查询卡片所属银行缩写
        $url = 'https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardBinCheck=true&cardNo='. $UserInfo['bank_card_number'];
        $res = curlPost($url,[]);
        if($res){
            $res = json_decode($res, true);
            # 获取银行卡颜色和图标     
            $BankInfoModel = new BankInfo();
            $BankInfo = $BankInfoModel->where("bank_abbreviation", $res['bank'])->find();
            $data[] = [
                'color'            => $BankInfo['color'],
                'logo_url'         => $BankInfo['logo_url'],
                'back_url'         => $BankInfo['back_url'],
                'bank_name'        => $BankInfo['bank_name'],
                'bank_card_number' => substr($UserInfo['bank_card_number'],-4),
            ];
        }

        return $data;
    }


    public function bankcardbindlistQuery_notice($arr)
    {

        $llpay_config = config('llpay');
        //计算得出通知验证结果
        $llpayNotify = new LLpayNotify($llpay_config);
        $sign = $arr['sign']; 
        // 订单查询验签
        $llpayNotify->verifyNotify_bankcardbindlist($arr,$sign);

        $data["res"] = $llpayNotify->result; 
        $data["data"] = $llpayNotify->notifyResp;
        return $data; 
    }
    /**
     * 银行卡解约
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-14T11:52:29+0800
     * @return      [type]                   [description]
     */
    public function bankcardunbind($param)
    {
        if(!($param['uid'])){
            $this->error = "没有获取到正确的用户信息";
            return false;
        }    

        if(!($param['no_agree'])){
            $this->error = "没有获取到正确的卡信息";
            return false;
        } 

        $applyModel = new Apply;
        $canBindBank = $applyModel->canBindBank($param['uid']);
        if($canBindBank == false){
            $this->error = "申请中不能操作";
            return false; 
        }

        // 不让解绑收款卡
        $UserInfoModel = new UserInfo;
        $UserInfo= $UserInfoModel->where('uid', $param['uid'])->field('no_agree,rand_code')->find();
        if($UserInfo['no_agree'] == $param["no_agree"]){
            $this->error = "收款账户不能解绑";
            return false; 
        }

        $llpay_config = config('llpay');
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "oid_partner"  =>  trim($llpay_config['oid_partner']),
            "sign_type"    =>  trim($llpay_config['sign_type']),
            "pay_type"     =>  trim($llpay_config['pay_type']),
            "user_id"      =>  $UserInfo['rand_code'],
            "no_agree"     =>  $param['no_agree'],
        );
        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);
        // 查询 订单信息
        $html_text = $llpaySubmit->buildbankcardunbindRequestHttp($parameter); 

        $res_Arr = json_decode($html_text,true);
        # 判断是否有 sign 如果没有 说明没有查询到 ，无需走验签流程
        if(!isset($res_Arr["sign"])){
            $this->error = $res_Arr["ret_msg"].":".$res_Arr["ret_code"];
            return false;
        } 
    
        $verify_res = $this->bankcardbindlistQuery_notice($res_Arr); 
// 返回示例       
// array(2) {
//   ["res"] => bool(true)
//   ["data"] => array(3) {
//     ["sign_type"] => string(3) "RSA"
//     ["ret_code"] => string(4) "0000"
//     ["ret_msg"] => string(12) "交易成功"
//   }
// }               
        if ($verify_res["res"]) { //验证成功
            if($verify_res["data"]["ret_code"]=="0000") {
                return true;
            }else {
                $this->error = "解绑失败";
                return false;
            }
        } else {
            $this->error = "返回结果验签失败";
            return false;
        } 
    }
/**
 * 银行卡扣款代扣
 * @author   yhq <934797303@qq.com>
 * @DateTime 2017-10-20T12:03:10+0800
 * @param    [type]                   $param [description]
 * @return   [type]                          [description]
 */
    public function repayment($param)
    {   
        $UserInfoModel = new UserInfo();
        $UserInfo = $UserInfoModel->where('uid',$res['uid'])->field('rand_code')->find();
        $param['rand_code'] = $UserInfo['rand_code'];

        $time_stamp = date('YmdHis');
        //支付类型
        $busi_partner = $param['busi_partner'] ? $param['busi_partner'] : 101001;
        //风险控制参数
        $risk_item = array(
            'frms_ware_category' => 2010, //商品类目传 2010
            'user_info_mercht_userno' => $param['rand_code'], //用户id
            'user_info_bind_phone' => $param['bind_phone'],  //用户手机号
            'user_info_dt_register' => $time_stamp, //用户注册时间 格式：YYYYMMDDH24MISS 14 位数字，精确到秒
            'user_info_identify_state' => 1, //是否实名认证
            'user_info_identify_type' => 4, //实名认证方式
            'user_info_full_name' => $param['name'], //用户姓名
            'user_info_id_no' => $param['id_card'] //用户身份证号
        );

        $llpay_config = config('llpay');
        //构造要请求的参数数组，无需改动
        $parameter = array (
            "dt_order"                => $time_stamp,
            "api_version"             => '1.0',
            "sign_type"               => trim($llpay_config['sign_type']),
            "oid_partner"             => trim($llpay_config['oid_partner']),
            "app_request"             => trim($llpay_config['app_request']),
            "busi_partner"            => $busi_partner,
            "user_id"                 => $param['rand_code'],
            "goods_name"              => '小额银行卡代扣',
            "money_order"             => $param['money_order'],
            "no_order"                => $param['no_order'],
            "risk_item"               => $risk_item,
            "id_no"                   => $param['id_card'],
            "card_no"                 => $param['bank_card_number'],
            "notify_url"              => $this->notify_url,//待填写
            "schedule_repayment_date" => date('Y-m-d',time()),
            'repayment_no'            => $param['repayment_no'],
            'pay_type'                => 'D',
            'no_agree'                => $param['no_agree'],
        );
        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);
        $html_text = $llpaySubmit->repaymentRequestHttp($parameter);

        $res_Arr = $this->object_array(json_decode($html_text));
        # 判断是否有 sign 如果没有 说明没有查询到 ，无需走验签流程
        if(!isset($res_Arr["sign"])){
            $this->error = $res_Arr["ret_msg"].":".$res_Arr["ret_code"];
            return false;
        } 
    
        $verify_res = $this->bankcardunbind_notice($html_text); 
        if ($verify_res["res"]) { //验证成功
            if($verify_res["data"]["ret_code"]=="0000") {
                return true;
            }else {
                $this->error = $verify_res["data"]["ret_msg"];
                return false;
            }
        } else {
            $this->error = "返回结果验签失败";
            return false;
        } 

    }
    /**
     * [changePlan 更改计划]
     * @return [type] [description]
     */
    public function changePlan($apply_id = '')
    {
        $UserInfoModel = new UserInfo();
        $UserInfo = $UserInfoModel->where('uid',$res['uid'])->field('rand_code')->find();
        $param['rand_code'] = $UserInfo['rand_code'];
        if(!$apply_id)
        {
            $this->error = '参数错误';
        }
        $pay = new LPay();
        $userInfo = $pay->getAgreenoData($apply_id,1);
        $llpay_config = config('llpay');
        $sms_param =  json_encode(['contract_type'=>'土豪钱庄','contact_way'=>'0000']);
        $parameter = [
            "oid_partner" => $llpay_config['oid_partner'],
            "sign_type" => $llpay_config['sign_type'],
            "sms_param"  => $sms_param,
            "user_id"  => $param['rand_code'],
            "repayment_plan"  => $userInfo['repayment_plan'],
            "repayment_no"  => $userInfo['contract_number'],
        ];
        //建立请求
        $llpaySubmit = new LLpaySubmit($llpay_config);

        $html_text = $llpaySubmit->repaymentPlanRequestHttp($parameter);
        $html_text_arr = $this->object_array(json_decode($html_text));

        # 判断是否有 sign 数据
        if(!isset($html_text_arr["sign"])){
            $this->error = $html_text_arr["ret_msg"];
            return false;
        }
        die;
        $llpayNotify = new LLpayNotify($llpay_config);
        $sign = $html_text_arr['sign']; 
        // 查询验签
        # 调用验签方法
        $llpayNotify->verifyNotify_bankcardbindlist($html_text_arr,$sign);
        $notice_res["res"] = $llpayNotify->result; 
        $notice_res["data"] = $llpayNotify->notifyResp;
        if(!$notice_res["res"]){
            $this->error = "验签失败";
            return false;
        }
        
        if($notice_res["data"]["ret_code"]=="0000"){
            return true;
        } else {
            $this->error = $notice_res["data"]["ret_msg"].":".$notice_res["data"]["ret_code"];
            return false;
        }
    }
    public function bankcardunbind_notice($str)
    {

        $llpay_config = config('llpay');
        //计算得出通知验证结果
        $llpayNotify = new LLpayNotify($llpay_config);
        // 订单查询验签
        $llpayNotify->verifyNotify_bankcardunbind($str);

        $data["res"] = $llpayNotify->result; 
        $data["data"] = $llpayNotify->notifyResp;
        return $data; 
    }    
    public function object_array($array) 
    {  
        if (is_object($array)) {  
            $array = (array)$array;  
        } 
        if (is_array($array)) {  
            foreach ($array as $key=>$value) {  
                $array[$key] = $this->object_array($value);  
            }  
        }  
        return $array;  
    }     

}
